package org.ma.basic.interceptors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("你已经进入了拦截器。。。。。");
        // 判断每个请求是否都带了 token
        String token = request.getHeader("token");
        if (Objects.isNull(token)){
            PrintWriter writer = response.getWriter();
//            AjaxResult ajaxResult = AjaxResult.me().setSuccess(false).setMessage("noLogin");
//            writer.print(ajaxResult);
            writer.print("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }
        Object o = redisTemplate.opsForValue().get(token);
        // 如果带了token 就去redis里面 获取 logininfo 数据
        if (Objects.isNull(o)){
            PrintWriter writer = response.getWriter();
//            AjaxResult ajaxResult = AjaxResult.me().setSuccess(false).setMessage("noLogin");
//            writer.print(ajaxResult);
            writer.print("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }
        // 续费
        redisTemplate.expire(token,30,TimeUnit.MINUTES);
        // 有就放行
        return true;
    }
}
